import java.util.Random;
public class VillageMixer 
{
	
	private Village[] originalVillages;
	private Village[] mixedVillages;
	
	public VillageMixer(Village[] villages)
	{
		originalVillages = villages;
		mixedVillages = new Village[villages.length];
		mix();
	}
	
	private void mix()
	{
		int playersPerVillage = originalVillages[0].returnPlayers().length;
		int numberOfVillages = originalVillages.length;
		
		// The number of players total equals the # of villages X # of players per village
		// This assumes that all villages have an equal amount of players.
		Team8_Player[] allPlayers = new Team8_Player[numberOfVillages * playersPerVillage];
		
		int playerTracker = 0;
		
		
		//Add all the players from all the villages to the allPlayers array, mixing the order as they are added
		for(int i = 0; i < playersPerVillage; i++)
		{
			for(int j = 0; j < numberOfVillages; j++)
			{				
				allPlayers[playerTracker] = originalVillages[j].returnPlayers()[i];
				playerTracker++;
			}
		}
		
		//scramble up the top players from each village
		Random random = new Random();
		for(int i = 0; i < numberOfVillages*2; i++)
		{
			Team8_Player temp = allPlayers[i];
			int rand = random.nextInt(allPlayers.length);
			allPlayers[i] = allPlayers[rand];
			allPlayers[rand] = temp;
		}
		
		playerTracker = 0;
		
		//Puts players into their new villages
		for(int i = 0; i < numberOfVillages; i++)
		{
			Team8_Player[] villagers = new Team8_Player[playersPerVillage]; 
			
			for(int j = 0; j < playersPerVillage; j++)
			{
				villagers[j] = allPlayers[playerTracker];
				playerTracker++;
			}
			
			Village tempVillage = new Village(villagers);
			mixedVillages[i] = tempVillage;
		}
	}
	
	public Village[] returnMixedVillages()
	{
		return mixedVillages;
	}

}
